package com.qf.chat.service.impl;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.chat.commons.exception.ServiceException;
import com.qf.chat.commons.r.Codes;
import com.qf.chat.dao.UserDao;
import com.qf.chat.entity.User;
import com.qf.chat.entity.vo.UserLoginVo;
import com.qf.chat.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2024-01-12 10:46:27
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {


    @Override
    public boolean save(User entity) {
        //验证用户名是否存在
        User user = this.query().eq("username", entity.getUsername()).one();
        if (user != null) {
            //用户名已经存在
            throw new ServiceException(Codes.USER_EXISTS);
        }

        //MD5 -> 摘要/Hash算法（明文 -> MD5 -> 32位字符串）
        //密码加密
        entity.setPassword(MD5.create().digestHex(entity.getPassword()));

        //昵称转拼音
        String pinyin = PinyinUtil.getPinyin(entity.getNickname()).replace(" ", "");
        entity.setPinyin(pinyin);

        //保存用户信息
        return super.save(entity);
    }

    /**
     * 根据用户名和密码查询用户信息
     * @return
     */
    @Override
    public User queryUserByUsernameAndPassword(UserLoginVo userLoginVo){
        return this.query()
                .eq("username", userLoginVo.getUsername())
                .eq("password", MD5.create().digestHex(userLoginVo.getPassword()))
                .one();
    }

    @Override
    public User queryUserByUserName(String username) {
        return this.query().eq("username", username).one();
    }

    /**
     * 修改用户密码
     * @param username
     * @param password
     * @return
     */
    @Override
    public int updateUserPassword(String username, String password) {
        this.update().set("password", MD5.create().digestHex(password))
                .eq("username", username)
                .update();

        //update xxxx set xxx=xxxx where xxx=xxx
        return 1;
    }

    @Override
    public List<User> searchUserByKeyword(String keyword) {
        if (!StringUtils.hasLength(keyword)) return null;
        return this.query()
                .like("nickname", keyword)
                .or()
                .likeRight("pinyin", keyword)
                .or()
                .like("username", keyword)
                .list();
    }
}

